layui.use(['form', 'jquery', 'layer', 'table', 'laydate', 'laypage'], function() {
	var form = layui.form;
	var $ = layui.$;
	var table = layui.table;
	var layer = layui.layer;
	var laydate = layui.laydate;
	var laypage = layui.laypage;
	var upload = layui.upload;

	var table_filter = 'pikuan_list',
		where_json = {
			_o: 'pk_id',
			_b: 'desc'
		},
		form_filter = 'pikuan_search_form';
	// 渲染表格
	if (load_data === true) {
		table.render({
			elem: '#' + table_filter,
			id: table_filter,
			url: pikuan_list_url,
			method: 'post',
			height: 'full-200',
			where: {
				_o: 'pk_id',
				_b: 'desc'
			},
			cols: [pikuan_cols],
			page: {
				layout: ['count', 'first', 'prev', 'page', 'next', 'last', 'skip'],
				limit: 30,
				theme: '#393d49',
				groups: 8
			},
			autoSort: false,
			toolbar: '#pikuanToolbar',
			initSort: {
				field: 'pk_id',
				type: 'desc'
			},
			done: function(res, curr, count) {
				layuiRowspan(res.data, ['pk_id', 'return_code', 'pay_time', 'renkuanshijian',
					'beizhu', 'create_time', 'title', 'money', 'state', 'zhiyi_state',
					'oprate', 'zhiyi_order', 'reject_reason', 'admin_name', 'qiantai'
				]);
			}
		});
	}


	upload.render({
		elem: '#qiantai',
		url: upload_qiantai,
		acceptMime: 'application/vnd.ms-excel',
		auto: true,
		accept: 'file',
		exts: 'xls',
		multiple: false,
		drag: false,
		before: function(obj) {
			layer.load();
		},
		done: function(res, index, upload) {
			if (res.code == 0) {
				layer.closeAll('loading');
				layer.msg(res.msg, {
					icon: 3
				});
				return false;
			}
			table.reload('pikuan_list')
			/* pkd_data_arr = res.data;
			$('.oprate-div').show();
			table.init('pikuan', {
				done: (r) => {
					let table = $('.layui-table-view[lay-id="pikuan"]').find(
						'table tbody')
					r.data.forEach((e, i) => {
						if (e.open > 0) {
							td = table.find('tr[data-index="' + i + '"]').find(
									'td:first').find('.laytable-cell-checkbox')
								.hide()
						}
					})
				}
			}) */
			layer.closeAll('loading');
		},
		error: function(index, upload) {
			layer.msg('excel格式错误', {
				icon: 2
			});
			layer.closeAll('loading');
		}
	});



	upload.render({
		elem: '#yipikuan',
		url: upload_ypk,
		acceptMime: 'application/vnd.ms-excel',
		auto: true,
		accept: 'file',
		exts: 'xls',
		multiple: false,
		drag: false,
		before: function(obj) {
			layer.load();
		},
		done: function(res, index, upload) {
			if (res.code == 0) {
				layer.closeAll('loading');
				layer.msg(res.msg, {
					icon: 3
				});
				return false;
			}
			table.reload('pikuan_list')
			/* pkd_data_arr = res.data;
			$('.oprate-div').show();
			table.init('pikuan', {
				done: (r) => {
					let table = $('.layui-table-view[lay-id="pikuan"]').find(
						'table tbody')
					r.data.forEach((e, i) => {
						if (e.open > 0) {
							td = table.find('tr[data-index="' + i + '"]').find(
									'td:first').find('.laytable-cell-checkbox')
								.hide()
						}
					})
				}
			}) */
			layer.closeAll('loading');
		},
		error: function(index, upload) {
			layer.msg('excel格式错误', {
				icon: 2
			});
			layer.closeAll('loading');
		}
	});


	var layuiRowspan = function(data, rowspan) {
		let init_pk_id = 0
		let obj_table = $('.layui-table-view[lay-id="pikuan_list"]').find('.layui-table-body').find('table')
			.find('tbody')
		data.forEach((e, index) => {
			let tr = obj_table.find('tr[data-index="' + index + '"]'),
				rowspan_num = e.order.length ? e.order.length : 1;
			if (e.pk_id != init_pk_id) {
				init_pk_id = e.pk_id
				// 找到对应
				for (let i = 0; i < rowspan.length; i++) {
					tr.find('td[data-field="' + rowspan[i] + '"]').attr('rowspan', rowspan_num)
				}
			} else {

				for (let i = 0; i < rowspan.length; i++) {
					tr.find('td[data-field="' + rowspan[i] + '"]').css({
						'display': 'none'
					})
				}
			}
		})
	};



	// 编辑表格
	// 表格工具监听
	table.on('tool(' + table_filter + ')', function(obj) {
		var data = obj.data;
		var e = obj.event;
		var tr = obj.tr;
		var returned_id = data.returned_id;
		switch (e) {
			case 'over':
				layer.confirm('完成后不能再质疑，确定完成吗？', {
						icon: 3
					},
					function() {
						send_info(over_url, {
							pk_id: data.pk_id
						}, function(res) {
							obj.update({
								state: 2
							})
							table.reload(table_filter, {}, true)
							layer.closeAll()
							layer.msg('操作成功', {
								icon: 1
							})
						})
					}
				)
				break;
			case 'pass':
				// 校验订单是否已认款
				var title = data.state == 1 ? '审核通过将回滚订单支付状态，是否通过？' : '审核通过将设置订单支付状态，是否通过？'
				send_info(chk_order_url, {
					order_nos: data.zhiyi_order
				}, (res) => {
					if (res.code == 1) {
						title = '该订单已认款，认款抬头是：' + res.data + '，是否通过？'
					}
					layer.confirm(title, {
						icon: 3
					}, function() {
						send_info(pass_url, {
							pk_id: data.pk_id
						}, function(res) {
							obj.update({
								state: 1,
								zhiyi_state: 1
							})
							table.reload(table_filter, {}, true)
							layer.closeAll()
							layer.msg('操作成功', {
								icon: 1
							})
						})
					})
				})

				break;
			case 'reject':
				layer.prompt({
					title: '请输入驳回原因'
				}, function(value, index, elem) {
					send_info(reject_url, {
						pk_id: data.pk_id,
						reject_reason: value
					}, function(res) {
						obj.update({
							zhiyi_state: 2,
							reject_reason: value
						})
						table.reload(table_filter, {}, true)
						layer.closeAll()
						layer.msg('操作成功', {
							icon: 1
						})
					})
				})
				break;
			case "view":
				send_info(viewZhiyiOrder_url, {
					pk_id: obj.data.pk_id
				}, function(res) {
					var tr = ''
					var order_state = [
						'无效订单号',
						'待确认',
						'待发货',
						'待支付',
						'待收货',
						'已完成',
						'已退货',
						'已取消',
						'待妥投',
						'已废止'
					]
					if(res.data.pikuan.is_mul == 1){
						$('#is_mul').show();
						$('#mul_code').html(res.data.pikuan.mul_code)
					} else {
						$('#is_mul').hide();
					}
					// 创建 表格内容
					res.data.data.forEach((e, i) => {
						let cart_td = ''
						e.cart.forEach((e1, i1) => {
							cart_td += e1.fpmc + ';'
						})
						tr += '<tr>'
						tr += `
							<td>${e.contacts}</td>
							<td>${e.phone}</td>
							<td>${e.province + e.city + e.area + e.street}</td>
							<td>${e.out_order_no}</td>
							<td>${cart_td}</td>
							<td>${e.huikuandanwei}</td>
							<td>${e.company_name}</td>
							<td>${e.yonghu_beizhu||'无'}</td>
							<td>${order_state[e.jun_order_state]}</td>
							<td>${e.order_money/100}</td>
						`
						tr += '</tr>'
					})
					$('#order_info_box_1').html(tr)

					// 匹款信息列表
					var xx_list = ''
					res.msg.forEach((e) => {
						xx_list +=
							`<tr><td>${e.fkdw}</td><td>${e.address}</td><td>${e.phone}</td><td>${e.xxp}</td></tr>`
					})
					$('#pkxx_box_1').html(xx_list)

					layer.open({
						type: 1,
						shade: 0,
						offset: 'r',
						area: ['960px', '680px'],
						title: '质疑订单详情', //不显示标题
						content: $(
							'.order_info_1'
						), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
						cancel:function(){
							$('.order_info_1').hide();
						}
					});
				})
				break;
			default:
				break;
		}
	})

	// 监听表头按钮
	table.on('toolbar(' + table_filter + ')', function(obj) {
		var filter_url = $(this).attr('data-url');
		switch (obj.event) {
			case 'allPass':
				var checkStatus = table.checkStatus(table_filter);
				var check_flag = 1,
					id_arr = new Array();
				checkStatus.data.forEach((e, i) => {
					if (e.zhiyi_state != 0) {
						check_flag = 0
					}
					id_arr.push(e.pk_id)
				})
				if (check_flag != 1) {
					layer.msg('勾选的数据中，存在已处理的数据！', {
						icon: 2
					})
					return false
				}
				if (id_arr.length == 0) {
					layer.msg('请选择操作数据', {
						icon: 2
					})
					return false
				}
				layer.confirm('审核通过将设置或回滚订单支付状态，是否通过？', {
					icon: 3
				}, function() {
					send_info(passmul_url, {
						data: id_arr
					}, function(data) {
						layer.msg('操作成功', {
							icon: 1
						})
						table.reload('pikuan_list')
					})
				})

				break;
			case 'allReject':
				var checkStatus = table.checkStatus(table_filter);
				var check_flag = 1,
					id_arr = new Array();
				checkStatus.data.forEach((e, i) => {
					if (e.zhiyi_state == 2) {
						check_flag = 0
					}
					id_arr.push(e.pk_id)
				})
				if (check_flag != 1) {
					layer.msg('勾选的数据中，存在已驳回的数据！', {
						icon: 2
					})
					return false
				}
				if (id_arr.length == 0) {
					layer.msg('请选择操作数据', {
						icon: 2
					})
					return false
				}
				layer.prompt({
					title: '请输入驳回原因'
				}, function(value, index, elem) {
					send_info(rejectmul_url, {
						data: id_arr,
						reject_reason: value
					}, function(res) {
						layer.msg('操作成功', {
							icon: 1
						})
						table.reload('pikuan_list')
					})
				})
				break;
			case 'importPikuan':
				layer.open({
					type: 2,
					anim: -1,
					title: '匹款',
					closeBtn: true,
					offset: 'r',
					shade: 0.3,
					move: false,
					shadeClose: true,
					area: '90%',
					skin: "layui-anim layui-anim-rl layui-layer-adminRight",
					content: filter_url
				})
				break;
			case 'exportrk':
				// 导出当前查询结果
				send_info(exportrk_url, {
					...where_json
				}, function(data) {
					layer.closeAll();
					layer.open({
						type: 2,
						title: '下载excel',
						content: data.data
					});
				})
				break;
		}
	})


	// 排序
	table.on('sort(' + table_filter + ')', function(data) {
		var _o = data.field;
		var _b = data.type;
		table.reload(table_filter, {
			initSort: data,
			where: {
				_o: _o,
				_b: _b
			}
		})
	})

	// 回款时间
	var pay_time_start_3 = laydate.render({
		elem: '#pay_time_start_3',
		max: 1,
		theme: '#393D49',
		done: function(value, date, endDate) {
			if (value) {
				pay_time_end_3.config.min = {
					year: date.year,
					month: date.month - 1,
					date: date.date
				};
			}
			where_json['pay_time_start'] = value;
		}
	});
	var pay_time_end_3 = laydate.render({
		elem: '#pay_time_end_3',
		max: 1,
		theme: '#393D49',
		done: function(value, date, endDate) {
			if (value) {
				pay_time_start_3.config.max = {
					year: date.year,
					month: date.month - 1,
					date: date.date
				};
			}
			where_json['pay_time_end'] = value;
		}
	});
	// 认款时间
	var create_time_start_3 = laydate.render({
		elem: '#create_time_start_3',
		max: 1,
		theme: '#393D49',
		done: function(value, date, endDate) {
			if (value) {
				create_time_end_3.config.min = {
					year: date.year,
					month: date.month - 1,
					date: date.date
				};
			}
			where_json['create_time_start'] = value;
		}
	});
	var create_time_end_3 = laydate.render({
		elem: '#create_time_end_3',
		max: 1,
		theme: '#393D49',
		done: function(value, date, endDate) {
			if (value) {
				create_time_start_3.config.max = {
					year: date.year,
					month: date.month - 1,
					date: date.date
				};
			}
			where_json['create_time_end'] = value;
		}
	});

	form.render();

	// 表单input 查询
	$('form[lay-filter="' + form_filter + '"]').on('input propertychange', 'input[type="text"]', function() {
		if ($(this).prop('comStart')) return;
		var value = $(this).val();
		var name = $(this).attr('name');
		where_json[name] = value;
	}).on('compositionstart', 'input[type="text"]', function() {
		$(this).prop('comStart', true);
	}).on('compositionend', 'input[type="text"]', function() {
		$(this).prop('comStart', false);
		$(this).trigger('input');
	});

	form.on('select', function(data) {
		where_json[data.elem.attributes['lay-filter'].value] = data.value;
	})



	form.on('submit(pikuan_search_form)', function(data) {
		layer.load();
		table.reload(table_filter, {
			where: where_json,
			page: {
				curr: 1
			},
			done: function(res, curr, count) {
				layuiRowspan(res.data, ['pk_id', 'return_code', 'pay_time',
					'renkuanshijian', 'beizhu', 'create_time', 'title', 'money',
					'state', 'zhiyi_state', 'oprate', 'zhiyi_order',
					'reject_reason', 'admin_name', 'qiantai'
				]);
				layer.closeAll();
			}
		});
		return false
	})

})